import frappe

@frappe.whitelist()
def make_process_card_list(work_order_no):
    work_order_doc = frappe.get_doc("Work Order", work_order_no)
    if work_order_doc.docstatus !=1:
        frappe.throw("工单非提交状态，不能生成流程卡")
    if len(work_order_doc.process_card_list) > 0:
        frappe.throw("流程卡已生成，请勿重复操作")
    if work_order_doc.process_card_batch_size is None:
        frappe.throw("流程卡批量大小未设置")
    batch_size = work_order_doc.process_card_batch_size
    process_card_index = 1
    qty = work_order_doc.qty
    alloc_qty_total = 0
    while (True):
        rem_qty = qty - alloc_qty_total
        if rem_qty <= 0:
            break
        alloc_qty = min(rem_qty, batch_size)        
        work_order_doc.append("process_card_list", {
            "process_card_no": work_order_doc.name + "#" + f"{process_card_index:0{5}d}",
            "process_card_status": "未开始",
            "alloc_qty": alloc_qty, 
        })        
        alloc_qty_total += alloc_qty
        process_card_index += 1
    work_order_doc.flags.ignore_validate_update_after_submit = True
    work_order_doc.save(ignore_permissions=True) 
    frappe.db.commit()
    return "流程卡生成成功"

@frappe.whitelist()
def update_process_card_batch_size(work_order_no,batch_size):
    work_order_doc = frappe.get_doc("Work Order", work_order_no)
    if len(work_order_doc.process_card_list) > 0:
        frappe.throw("流程卡已生成，不能修改批次大小")
    work_order_doc.process_card_batch_size = batch_size
    work_order_doc.flags.ignore_validate_update_after_submit = True
    work_order_doc.save(ignore_permissions=True) 
    frappe.db.commit()
    return "批次设置成功"